import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例（开发环境支持代理，避免CORS）
const useProxy = import.meta?.env?.VITE_USE_PROXY === 'true'
const isDev = !!import.meta?.env?.DEV
const apiFromEnv = import.meta?.env?.VITE_API_BASE_URL
// 在开发且开启代理时，走本地相对路径 /api，从而被 Vite 代理到后端
// const API_BASE_URL = (isDev && useProxy) ? '/api' : (apiFromEnv || 'http://api-territory-game.monkeymeerkat.cn/api')
const API_BASE_URL = (isDev && useProxy) ? '/api' : (apiFromEnv || 'http://localhost:5004/api')
const request = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 添加token到请求头
    try {
      const tokenDataStr = localStorage.getItem('token')
      const tokenObj = tokenDataStr ? JSON.parse(tokenDataStr) : null
      const accessToken = tokenObj?.accessToken || localStorage.getItem('accessToken')
      if (accessToken) {
        config.headers.Authorization = `Bearer ${accessToken}`
      }
    } catch (error) {
      console.error('解析token失败:', error)
    }
    
    // 可以在这里添加loading状态
    // store.commit('setLoading', true)
    
    return config
  },
  (error) => {
    // store.commit('setLoading', false)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // store.commit('setLoading', false)
    
    // 返回response.data，保持与之前代码的兼容性
    // 这样handleApiResponse等函数就能正常工作
    return response.data
  },
  async (error) => {
    // store.commit('setLoading', false)
    
    const { response } = error
    const isSilent = error?.config?.meta?.silent === true
    
    if (response) {
      const { status, data } = response
      const isSilent = Boolean(error?.config?.silent)
      const silentCodes = error?.config?.silentCodes || []
      const messageText = (data && (data.message || data.msg)) || ''
      
      if (isSilent) {
        return Promise.reject(error)
      }
      
      switch (status) {
        case 400:
          if (isSilent || silentCodes.includes(400) || /已经在房间/.test(messageText)) {
            // 该错误将由调用方自行处理或忽略
          } else {
            ElMessage.error(messageText || '请求参数错误')
          }
          break
        case 401:
          // token过期，尝试刷新token
          if (!error.config._retry) {
            error.config._retry = true
            try {
              // 从多种位置读取 refreshToken
              let refreshToken = null
              const tokenDataStr = localStorage.getItem('token')
              if (tokenDataStr) {
                try { refreshToken = JSON.parse(tokenDataStr)?.refreshToken || null } catch {}
              }
              refreshToken = refreshToken || localStorage.getItem('refreshToken')
              if (refreshToken) {
                const refreshResponse = await request.post('/auth/refresh-token', { refreshToken }, { silent: true })
                const payload = refreshResponse?.data ? refreshResponse.data : refreshResponse
                const newAccessToken = payload?.accessToken
                const newRefreshToken = payload?.refreshToken
                if (newAccessToken) {
                  // 双写：既写聚合 token，也写分散的键，保证兼容
                  try {
                    const tokenObj = { accessToken: newAccessToken, refreshToken: newRefreshToken }
                    localStorage.setItem('token', JSON.stringify(tokenObj))
                  } catch {}
                  localStorage.setItem('accessToken', newAccessToken)
                  if (newRefreshToken) localStorage.setItem('refreshToken', newRefreshToken)
                  // 重新发送原请求
                  error.config.headers.Authorization = `Bearer ${newAccessToken}`
                  return request(error.config)
                }
              }
            } catch (refreshError) {
              // 刷新token失败，清除本地存储并跳转到登录页
              localStorage.removeItem('token')
              localStorage.removeItem('accessToken')
              localStorage.removeItem('refreshToken')
              localStorage.removeItem('user')
              if (!isSilent) ElMessage.error('登录已过期，请重新登录')
              window.location.href = '/login'
              return Promise.reject(refreshError)
            }
          } else {
            if (!isSilent) ElMessage.error('登录已过期，请重新登录')
          }
          break
        case 403:
          ElMessage.error('没有权限访问该资源')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          if (!isSilent) {
            ElMessage.error(messageText || '请求失败')
          }
      }
    } else {
      // 网络错误 - 只在控制台记录，不显示弹窗
      console.warn('网络连接失败，请检查网络设置:', error.message)
      
      // 只在特定情况下显示网络错误提示
      if (error.code === 'ERR_NETWORK' || error.code === 'ERR_INTERNET_DISCONNECTED') {
        // 这些是真正的网络连接问题，可以显示提示
        console.error('检测到网络连接问题:', error.code, error.message)
      }
    }
    
    return Promise.reject(error)
  }
)

// 通用API响应处理工具
export const handleApiResponse = (response, dataKey = 'data') => {
  console.log('handleApiResponse 输入:', response)
  
  // 如果响应是标准格式 {code, message, data, timestamp}
  if (response && typeof response === 'object' && 'code' in response) {
    // 检查是否成功
    if (response.code === 200) {
      const result = response[dataKey] || response
      console.log('handleApiResponse 输出:', result)
      return result
    } else {
      // 如果code不是200，抛出错误
      throw new Error(response.message || '请求失败')
    }
  }
  
  // 如果响应不是标准格式，直接返回
  console.log('handleApiResponse 直接返回:', response)
  return response
}

// 封装请求方法
export const http = {
  // GET请求
  get: (url, params = {}, config = {}) => {
    return request.get(url, { params, ...config })
  },
  
  // POST请求
  post: (url, data = {}, config = {}) => {
    return request.post(url, data, config)
  },
  
  // PUT请求
  put: (url, data = {}, config = {}) => {
    return request.put(url, data, config)
  },
  
  // DELETE请求
  delete: (url, config = {}) => {
    return request.delete(url, config)
  },
  
  // PATCH请求
  patch: (url, data = {}, config = {}) => {
    return request.patch(url, data, config)
  }
}

// 导出axios实例，以便需要时直接使用
export default request
